package client.global.commlib.network

import android.util.Log
import client.global.commlib.BuildConfig
import client.global.commlib.ContextProvider
import client.global.commlib.utils.SharedUtil
import client.global.commlib.utils.Util
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.Proxy
import java.net.URLDecoder
import java.util.concurrent.TimeUnit


class HhRetroHttp private constructor() {
    private val mRetrofit: Retrofit by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(7, TimeUnit.SECONDS)
            .readTimeout(7, TimeUnit.SECONDS)
            .proxy(Proxy.NO_PROXY)
            .addInterceptor(object : Interceptor {
                @Throws(IOException::class)
                override fun intercept(chain: Interceptor.Chain): Response {
                    val ts = System.currentTimeMillis().toString() + ""
                    val token =
                        SharedUtil.read("token", "") as String
                    var version = 0

                    ContextProvider.get().activity?.let {
                        version = it
                            .packageManager
                            .getPackageInfo(it.packageName, 0).versionCode
                    }
                    val request: Request = chain.request().newBuilder()
                        .addHeader("access", "&OSpYVy#6g^Q7Fo#")
                        .addHeader("ts", ts)
                        .addHeader("version", "${version}")
                        .addHeader("sign", Util.getSign(ts))
                        .addHeader("token", token)
                        .build()
                    return chain.proceed(request)
                }
            })
            .addInterceptor(
                HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY }
            )
            .build()

        Retrofit.Builder()
            .baseUrl(BuildConfig.API_URL)
//            .addConverterFactory(CustomGsonConverterFactory().apply {
//                gson = Gson()
//            })
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
    }

    companion object {

        private val INSTANT: HhRetroHttp by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { HhRetroHttp() }

        fun get(): HhRetroHttp {
            return INSTANT
        }

        fun <T> createApi(tClass: Class<T>): T {
            return lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { get().mRetrofit.create(tClass) }.value
        }
    }


}